/*
 * The MIT License
 *
 * Copyright 2012 http://generic-toolset.googlecode.com.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.rlpw.lang;

import java.lang.annotation.*;
import java.util.HashMap;
import java.util.List;
import org.rlpw.util.ClassUtils;

/**
 * A static helperclass for factory baseclasses, which provides
 * an annotation driven access to the classes, the factory should
 * build and a cache to tweak the runtime speed a bit.
 *
 * <p> For further details about the annotation see:
 * {@link org.rlpw.lang.Factory.FactoryEntry}
 *
 * <p><b>Implementation Example:</b></p>
 * <pre>
public abstract class MyFactory {
    // creates default derivation of MyFactory
    public static MyFactory make() throws Exception {
        return Factory.make(MyFactory.class);
    }

    // creates named derivatin of MyFactory
    public static MyFactory make(String name) throws Exception {
        return Factory.make(MyFactory.class, name);
    }

    // abstract/general fields and methods
}
</pre>
 *
 * @author <a href="ronny.luettke@gmx.de">Ronny Lüttke</a>
 */
public final class Factory {

    @SuppressWarnings("rawtypes")
	private static HashMap<Class, HashMap<String, Class>> classCache = new HashMap<>();
    public final static String DEFAULT = "*";

    private Factory() {
        throw new InstantiationError("Factory shouldn't be instantiatet.");
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T make(Class<T> clazz, String name) throws Exception {
        HashMap<String, Class> cm = getGroup(clazz);
        if (cm != null) {
            if (cm.containsKey(name)) {
                return (T) cm.get(name).newInstance();
            }
            throw new ClassNotFoundException("Couldn't find the entry \"" + name + "\" for baseclass " + clazz.getName());
        }
        throw new ClassNotFoundException("Couldn't find entries for baseclass " + clazz.getName());
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T make(Class<T> clazz) throws Exception {
        HashMap<String, Class> cm = getGroup(clazz);
        if (cm != null) {
            if (cm.containsKey(DEFAULT)) {
                return (T) cm.get(DEFAULT).newInstance();
            }
            return (T) cm.values().toArray()[0];
        }
        throw new ClassNotFoundException("Couldn't find entries for baseclass " + clazz.getName());
    }
    
    public static String[] getEntriesFor(Object o) {
        FactoryEntry fe = (FactoryEntry) o.getClass().getAnnotation(FactoryEntry.class);
        if (fe != null) {
            return fe.value();
        }
        return new String[]{};
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	private static HashMap<String, Class> getGroup(Class clazz) throws Exception {
        if (!classCache.containsKey(clazz)) {
            List<Class> cs = ClassUtils.getClasses(clazz);
            HashMap<String, Class> cm = new HashMap<>();
            for (Class c : cs) {
                if (ClassUtils.isChildOf(c, clazz)) {
                    FactoryEntry fe = (FactoryEntry) c.getAnnotation(FactoryEntry.class);
                    if (fe != null) {
                        for (int i = 0; i < fe.value().length; i++) {
                            cm.put(fe.value()[i], c);
                        }
                    }
                }
            }
            if (cm.size() > 0) {
                classCache.put(clazz, cm);
            }
        }

        return classCache.get(clazz);
    }

    /**
     * Annotation for classes derived of factories which use {@link org.rlpw.lang.Factory}.
     *
     * <p>Single or multiple aliases are supported as strings:
     *
     * <p>single:
     * <pre>  @FactoryEntry("implementation1") </pre>
     * multiple as array:
     * <pre>  @FactoryEntry({"impl2","impl3"}) </pre>
     * you also can define a default class with <tt>Factory.DEFAULT</tt>:
     * <pre>  @FactoryEntry({"impl4",Factory.DEFAULT})</pre>
     * if no default is specified, the first found class is choosen
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface FactoryEntry {

        String[] value();
    }
}
